import AppKit
import AVFoundation
import ScreenSaver

extension NSNotification.Name {
    static let muteStateChanged = Notification.Name("muteStateChanged")
}

class WallpaperManager {
    static var previewWindow: NSWindow?
    
    static func showPreviewWindow() {
        if previewWindow == nil {
            previewWindow = NSWindow(
                contentRect: NSScreen.main?.frame ?? .zero,
                styleMask: [.titled, .closable, .miniaturizable, .resizable],
                backing: .buffered,
                defer: false
            )
            previewWindow?.title = "壁纸预览"
            previewWindow?.backgroundColor = .white
            previewWindow?.center()
        }
        
        previewWindow?.makeKeyAndOrderFront(nil)
    }
    
    static func setWallpaper(with url: URL, isVideo: Bool, for screen: NSScreen? = nil) throws {
        let targetScreen = screen ?? NSScreen.main ?? NSScreen.screens.first!
        try DisplayManager.shared.setWallpaper(url: url, isVideo: isVideo, for: targetScreen)
    }
    
    static func resetWallpaper(for screen: NSScreen? = nil) throws {
        let targetScreen = screen ?? NSScreen.main ?? NSScreen.screens.first!
        try DisplayManager.shared.resetWallpaper(for: targetScreen)
    }
    
    static func togglePlayPause(for screen: NSScreen? = nil) {
        let targetScreen = screen ?? NSScreen.main ?? NSScreen.screens.first!
        DisplayManager.shared.togglePlayPause(for: targetScreen)
    }
    
    static func setVolume(_ volume: Float, for screen: NSScreen? = nil) {
        let targetScreen = screen ?? NSScreen.main ?? NSScreen.screens.first!
        DisplayManager.shared.setVolume(volume, for: targetScreen)
    }
    
    static func toggleMute(for screen: NSScreen? = nil) {
        let targetScreen = screen ?? NSScreen.main ?? NSScreen.screens.first!
        DisplayManager.shared.toggleMute(for: targetScreen)
        NotificationCenter.default.post(name: Notification.Name("muteStateChanged"), object: nil)
    }
    
    static func getWallpaperState(for screen: NSScreen? = nil) -> DisplayManager.WallpaperState? {
        let targetScreen = screen ?? NSScreen.main ?? NSScreen.screens.first!
        return DisplayManager.shared.getWallpaperState(for: targetScreen)
    }
    
    static func isMuted(for screen: NSScreen? = nil) -> Bool {
        let targetScreen = screen ?? NSScreen.main ?? NSScreen.screens.first!
        return DisplayManager.shared.getWallpaperState(for: targetScreen)?.isMuted ?? false
    }
}